<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;

class Franchise extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'franchise';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'opening_time_text'
    ];


    public function getOpeningTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['opening_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setOpeningTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    /**
     * Notes: 添加 加盟信息
     * User: chenLei
     * Date: 7/18/25
     * @param $params
     * @return true
     * @throws \think\Exception
     */
    public function add($params)
    {
        $ip = request()->ip();
        $start_time = strtotime(date('Y-m-d 00:00:00'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));

        if ($this->where('ip', $ip)->where('createtime', 'between time', [$start_time, $end_time])->count() >= 3) {
            $this->error = 'You have submitted 3 pieces of franchise information today. Please do not submit them again';
            return false;
        }

        $this->save([
            'name' => $params['name'],
            'phone' => $params['phone'],
            'email' => $params['email'],
            'city' => $params['city'],
            'shop_address' => $params['shop_address'],
            'desc' => $params['desc'],
            'exits_exp' => $params['exits_exp'],
            'exp_desc' => $params['exp_desc'] ?? '',
            'budget' => $params['budget'],
            'opening_time' => $params['opening_time'],
            'remarks' => $params['remarks'] ?? '',
            'ip' => $ip,
        ]);

        return true;
    }

}
